<template>
  <div class="nut-price">
    <span v-html="priceShow"></span>
  </div>
</template>
<script>
import { isEmpty, divide } from 'lodash'
export default {
  name: 'PriceThousands',
  props: {
    price: {
      type: [Number, String],
      default: 0
    },
    needSymbol: {
      type: Boolean,
      default: true
    },
    // 小数位
    decimalDigits: {
      type: [Number, String],
      default: 2
    },
    // 以千位显示
    thousands: {
      type: Boolean,
      default: true
    },
    // 服务端数据转换
    convertUnit: {
      type: Boolean,
      default: false
    },
    currency: {
      type: String,
      default: '￥'
    }
  },
  data() {
    return {
    }
  },
  computed: {
    priceShow() {
      const currency = this.currency || ''
      const symbol = this.needSymbol ? `<span class="price-symbol">${currency}</span>` : ''
      return symbol + this.formatToHump(this.price)
    }
  },
  methods: {
    // 判断是否为小数点
    checkPoint(num) {
      return (String(num)).indexOf('.') > 0
    },
    formatToHump(num) {
      return `<span class="price-big">${this.formatThousands(num)}</span>`
    },
    // 根据小数位数格式化小数部分
    formatDecimal(decimalNum) {
      const decimalDigits = this.decimalDigits
      const result = `0.${String(decimalNum)}`
      const resultFixed = (result / 1).toFixed(decimalDigits)
      return String(resultFixed).substring(2, resultFixed.length)
    },
    // 千分位显示
    formatThousands(num) {
      let divideNum
      if (this.convertUnit) {
        divideNum = divide(num, 1000, 2)
      } else {
        divideNum = divide(num, 1, 2)
      }
      if (this.thousands) {
        const divideNumArr = divideNum.toString().split('.')
        const thousandsVal = (divideNumArr[0] || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
        if (!isEmpty(divideNumArr[1])) {
          return `${thousandsVal}.${divideNumArr[1]}`
        } else {
          return `${thousandsVal}`
        }
      } else {
        return num
      }
    }
  }
}
</script>
<style scoped>
.nut-price {
  display: inline;
}
</style>
